package com.micro.frog.rbac.controller;

import com.micro.frog.common.base.PageRes;
import com.micro.frog.common.base.Result;
import com.micro.frog.rbac.dto.RoleDTO;
import com.micro.frog.rbac.dto.UserDetail;
import com.micro.frog.rbac.entity.RoleDO;
import com.micro.frog.rbac.service.RoleService;
import com.micro.frog.rbac.util.SubjectUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 角色操作
 *
 * @author :  ljh
 * @date : 2018/4/12
 **/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "/rbac/role")
public class RoleController {

    private final RoleService roleService;

    /**
     * 带条件查询带分页
     */
    @GetMapping(value = "/page")
    public Result<PageRes<RoleDO>> listPage(RoleDTO req) {
        return roleService.queryPage(req);
    }

    /**
     * 查询全部不带分页
     */
    @GetMapping(value = "/list")
    public Result list(RoleDO role) {
        return Result.success(roleService.queryList(role));
    }

    @PostMapping("/add")
    public Result add(HttpServletRequest request, RoleDO role) {
        UserDetail user = SubjectUtil.getUser(request);
        role.setCreatedBy(user.getUserName());
        boolean flag = roleService.add(role);
        return flag ? Result.success("添加成功") : Result.error("添加失败");
    }

    @PostMapping("/delete")
    public Result delete(Long id) {
        boolean flag = roleService.delete(id);
        return flag ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/update")
    public Result update(HttpServletRequest request, RoleDO role) {
        UserDetail user = SubjectUtil.getUser(request);
        role.setUpdatedBy(user.getUserName());
        boolean flag = roleService.update(role);
        return flag ? Result.success("修改成功") : Result.error("修改失败");
    }
}
